package com.zhaotianhao.check.groupserver.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhaotianhao.check.groupserver.entity.Group;
import com.zhaotianhao.check.groupserver.entity.GroupVO;
import com.zhaotianhao.check.groupserver.entity.ItemGroup;
import com.zhaotianhao.check.groupserver.service.IGroupService;
import com.zhaotianhao.check.groupserver.service.IItemGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Z-7
 * @Date 2022/4/2
 */
@Slf4j
@Component
public class GroupTask {
    @Autowired
    private IGroupService iGroupService;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private IItemGroupService iItemGroupService;

    //@Scheduled(cron = "0 * * * * ?")
    public void syncRedis(){
        redisTemplate.delete("redisGroups");
        log.info("开始同步reids");
        List<Group> list = iGroupService.list();
        List<GroupVO> groupVOS = new ArrayList<>();
        list.forEach(item->{
            GroupVO groupVO = new GroupVO();
            BeanUtils.copyProperties(item,groupVO);
            QueryWrapper<ItemGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id",item.getId());
            List<ItemGroup> itemGroups = iItemGroupService.list(queryWrapper);
            List<Integer> itemIds = itemGroups.stream().map(iter -> iter.getId()).collect(Collectors.toList());
            groupVO.setIds(itemIds);
            groupVOS.add(groupVO);
        });
        log.info("存入reids");
        redisTemplate.opsForList().rightPush("redisGroups",groupVOS);
        log.info("存入reids结束");
    }
}
